<template>
  <div>
    <TopFilter ref="formpanel1" :list="formList1" :collapse="false" :isSubmitBtn="true" @filterChange="formchangeFun" />
    <FilterTable
      ref="basetable"
      :columns="columns"
      columnsRef="partPartInventoryAdjustInventoryAddNewPartPage"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'rows'"
      :onColumnsChange="columns => (this.columns = columns)"
      :height="'300'"
      :dataSource="toptablelist"
      :onEnterEvent="tableDbclickFun"
      selectionType="single"
      :onRowSelectChange="selectTableFun"
      :onSyncTableData="syncDataChange"
    ></FilterTable>
    <FormPanel ref="formpanel2" :list="formList2" labelWidth="120" :isSubmitBtn="false" @formChange="formchangeFuns" />
    <!-- <FilterTable
      ref="basetables"
      :columns="columns1"
      :dataSource="emptyTableData"
      :params="fetchParams"
      :datakey="'rows'"
      :onColumnsChange="columns1 => (this.columns1 = columns1)"
      :height="'200'"
      :onSyncTableData="tablechangeFun"
    ></FilterTable> -->
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9999,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeDialog">关 闭</el-button>
      <el-button type="primary" @click="confirmHandle">保 存</el-button>
    </div>
    <BaseDialog :visible.sync="pdiShow" title="借进入库单选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <newPartInfo :formData="formData" @cancel="closeHandler" @showOrder="showOrderDetail" />
    </BaseDialog>
    <!-- 库位 -->
    <BaseDialog :visible.sync="positionSelectVisible" title="库位选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <position :params="positionParams" @close="positionSelectVisible = false" @onConfirm="handlePositionSelectConfirm" />
    </BaseDialog>
  </div>
</template>
<script>
import axios from '@/api/fetch';
import SERVER from '@/api/server';
import { isAuthorized } from '@/utils/index';
import newPartInfo from './newPartInfo';
import { getStorageList, getaddPartList } from '@/api/part/partInventory/adjustInventory/index';
import { getPosition, getfindStorageCode } from '@/api/part/inventoryManager/inventoryManager/index';
import { queryBrand } from '@/api/part/partOut/partSales/index';
import { getStroageList } from '@/api/part/partOutbound/partBreak';
import { findAllRepair } from '@/api/repair/basicParameters';
import { dictionary } from '@/utils/dictMixin';
import { getBrand } from '@/api/repair/basicParameters';
import position from '@/pages/part/common/position';
export default {
  components: {
    newPartInfo,
    position
  },
  mixins: [dictionary],
  data() {
    return {
      formData: {},
      pdiShow: false, // 控制弹框
      pj: false,
      pd: false,
      formList1: this.createFrom(),
      formList2: this.createFroms(),
      fetchApi: this.getNewPartData,
      fetchParams: {
        xhrAbort: true,
        sort: '',
        queryPart_table: ''
      },
      columns: this.createTable(),
      columns1: this.createTables(),
      emptyTableData: [], // 用于清空表格数据
      toptablelist: [],
      tableslist: [],
      storageList: [],
      fromSubmitdata: {},
      // 是否显示替换件按钮
      isreplace: true,
      replacedata: {},
      // 仓库代码列表
      storageCodeList: [],
      // 名字
      storageNameList: [],
      styleList: [],
      partDetailTableData: {}, // 查询回来的配件数据
      positionSelectVisible: false, // 是否显示库位选择弹窗
      positionParams: {} // 库位查询参数
    };
  },
  created() {
    this.getlist();
  },
  mounted() {},
  methods: {
    // 点击库位搜索
    handleSearchPosition() {
      let storageCode = this.formList2.find(item => item.fieldName == 'STORAGE_CODE').initialValue;
      if (!storageCode) {
        return this.$notify.warning({ title: '提示信息', message: '请选择仓库' });
      }
      this.positionParams.storageCode = storageCode;
      this.positionParams.partNo = this.formList2.find(item => item.fieldName == 'partNo').initialValue;
      this.positionSelectVisible = true;
    },
    // 选择库位(弹窗)确定
    handlePositionSelectConfirm(val) {
      this.formList2.find(item => item.fieldName == 'STORAGE_POSITION_CODE').initialValue = val[0].storagePositionCode;
      this.positionSelectVisible = false;
    },
    syncDataChange(val) {
      this.styleList = [];
      val.forEach(x => {
        if (x.PART_STATUS == '10041001') {
          this.styleList.push({ row: x, styles: { backgroundColor: '#FB6fr5E1E3' } });
        }
      });
    },

    // 弹框确定
    showOrderDetail(val) {
      this.pdiShow = false;
      this.$emit('addNewPartnew', val);
    },
    // 弹框确定
    closeHandler() {
      this.pdiShow = false;
    },
    // 查询新增配件信息
    async getNewPartData(params) {
      const res = await axios.get(`${SERVER.DMSCLOUD_PART}/stockmanage/partbuy/findPartForAdd`, { params });
      if (res.data.rows.length === 0 && this.pj) {
        // this.$confirm('没有此配件，继续新增此配件吗?', '提示', {
        //   confirmButtonText: '确定',
        //   cancelButtonText: '取消',
        //   type: 'warning'
        // })
        //   .then(() => {
        // this.$emit('pdPartNo', params.partNo);
        // 执行方法  仓库和代码带过去
        this.pj = false;
        this.pd = true;
        this.formList2.find(x => x.fieldName == 'partNo').initialValue = params.partNo;
        this.partNo = params.partNo;
        this.formList2.find(x => x.fieldName == 'STORAGE_CODE').initialValue = params.storageCode;
        this.formList2.find(item => item.fieldName == 'STORAGE_POSITION_CODE').initialValue = '';
        this.queryEmptyLocation(params.storageCode);
        // })
        // .catch(() => {
        //   this.pd = false;
        //   this.pj = false;
        // });
      } else {
        this.pd = false;
        this.pj = false;
      }
      return res;
    },
    async queryEmptyLocation(val) {
      if (val) {
        let res = await getPosition({ storageCode: val });
        if (res.resultCode == 200) {
          if (res.data.length <= 0) {
            // this.$notify.warning({ title: '错误提示', message: '该仓库中没有库位可以使用' });
          } else {
            this.formList2.find(item => item.fieldName == 'STORAGE_POSITION_CODE').itemList = res.data.map(x => ({ text: x.storagePositionCode, value: x.storagePositionCode }));
          }
        }
      }
    },
    createFrom() {
      return [
        // {
        //   type: 'SELECT',
        //   label: '仓库',
        //   fieldName: 'storageCode',
        // clearable: false,
        // rules: [{ required: true, message: '请选择仓库', trigger: 'blur' }],
        //   itemList: []
        // },
        {
          type: 'INPUT',
          label: '配件代码',
          fieldName: 'partNo',
          rules: [
            { required: true, message: '请输入配件代码', trigger: 'blur' },
            { min: 2, message: '请输入至少两位配件代码', trigger: 'change' }
          ]
        },
        {
          type: 'SELECT',
          label: '品牌',
          fieldName: 'brand',
          itemList: []
        },
        {
          type: 'SELECT',
          label: '类别',
          fieldName: 'partGroupCode',
          itemList: this.createDictList('8075')
        },
        {
          type: 'INPUT',
          label: '拼音',
          fieldName: 'spellCode'
        },
        {
          type: 'INPUT',
          label: '名称',
          fieldName: 'partName'
        },
        // {
        //   type: 'INPUT',
        //   label: '库位',
        //   fieldName: 'storagePositionCode'
        // },
        {
          type: 'INPUT',
          label: '备注',
          fieldName: 'remark'
        }
      ];
    },
    createTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '仓库',
          dataIndex: 'STORAGE_CODE',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{this.getStroageName(props.row.STORAGE_CODE)}</span>;
          }
        },
        {
          title: '库位',
          dataIndex: 'STORAGE_POSITION_CODE',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{props.row.STORAGE_POSITION_CODE}</span>;
          }
        },
        {
          title: '配件代码',
          dataIndex: 'PART_NO',
          // sorter: true,
          width: 170,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件名称',
          dataIndex: 'PART_NAME',
          // sorter: true,
          showOverflowTooltip: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '含税销售价',
          dataIndex: 'SALES_PRICE',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number'
          // render: props => {
          //   return <span>{props.row.SALES_PRICE ? props.row.SALES_PRICE.toFixed(2) : '0.00'}</span>;
          // }
        },
        {
          // title: '不含税成本价',
          title: '不含税采购价',
          dataIndex: 'PLAN_PRICE',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2,
          hidden: !isAuthorized('1313', '13131005')
          // render: props => {
          //   return <span>{props.row.COST_PRICE ? props.row.COST_PRICE.toFixed(2) : '0.00'}</span>;
          // }
        },
        // {
        //   title: '终端建议零售价格',
        //   dataIndex: 'COST_PRICE',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'number',
        //   precision: 2
        // },
        {
          title: '可用库存',
          dataIndex: 'USEABLE_STOCK',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number',
          render: props => {
            return <span>{props.row.USEABLE_STOCK ? props.row.USEABLE_STOCK.toFixed(2) : '0.00'}</span>;
          }
        },
        {
          title: '账面库存',
          dataIndex: 'STOCK_QUANTITY',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number',
          render: props => {
            return <span>{props.row.STOCK_QUANTITY ? props.row.STOCK_QUANTITY.toFixed(2) : '0.00'}</span>;
          }
        },
        {
          title: '最大库存',
          dataIndex: 'MAX_STOCK',
          sorter: true,
          filter: true
        },
        {
          title: '最小库存',
          dataIndex: 'MIN_STOCK',
          sorter: true,
          filter: true
        },
        {
          title: '备注',
          dataIndex: 'REMARK',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{props.row.REMARK}</span>;
          }
        }
      ];
    },
    createFroms() {
      return [
        {
          type: 'SELECT',
          label: '仓库',
          fieldName: 'STORAGE_CODE',
          itemList: [],
          change: val => {
            this.formList2.find(x => x.fieldName == 'STORAGE_POSITION_CODE').initialValue = '';
            if (val != null && val != undefined && val != '') {
              this.queryEmptyLocation(val);
            } else {
              this.formList2.find(x => x.fieldName == 'STORAGE_POSITION_CODE').itemList = [];
            }
          }
          // rules: [{ required: true, message: '请输入仓库', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '库位',
          fieldName: 'STORAGE_POSITION_CODE',
          // itemList: []
          // rules: [{ required: true, message: '请选择库位', trigger: 'change' }],
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-search" onClick={this.handleSearchPosition}></el-button>;
          }
        },
        { type: 'INPUT', label: '配件代码', fieldName: 'partNo', rules: [{ required: true, message: '请输入配件代码', trigger: 'blur' }], disabled: true },
        { type: 'INPUT', label: '配件名称', fieldName: 'PART_NAME', rules: [{ required: true, message: '请输入配件名称', trigger: 'blur' }], disabled: true },
        {
          type: 'INPUT_NUMBER',
          label: '入库数量',
          // min: 0.01,
          fieldName: 'IN_QUANTITY',
          precision: 2,
          change: val => {
            this.changemNum(val);
          },
          rules: [{ required: true, message: '请输入入库数量', trigger: 'blur' }],
          disabled: false
        },
        {
          type: 'INPUT_NUMBER',
          label: '入库不含税单价',
          precision: 2,
          fieldName: 'inPrice',
          change: val => {
            this.changemoney(val);
          },
          rules: [{ required: true, message: '请输入入库不含税单价', trigger: 'blur' }],
          disabled: false
        },
        {
          type: 'INPUT_NUMBER',
          label: '入库不含税金额',
          precision: 2,
          fieldName: 'inAmount',
          rules: [{ required: true, message: '请输入入库不含税金额', trigger: 'blur' }],
          disabled: true
        }
      ];
    },
    createTables() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        { title: '销售价', dataIndex: 'SALES_PRICE', sorter: true, filter: true, filterType: 'input', precision: 2 },
        { title: '索赔价', dataIndex: 'CLAIM_PRICE', sorter: true, filter: true, filterType: 'input', precision: 2, hidden: !isAuthorized('1313', '13131006') },
        { title: '终端建议零售价格', dataIndex: 'INSURANCE_PRICE', sorter: true, filter: true, filterType: 'input', precision: 2 },
        { title: '最低销售限价', dataIndex: 'MIN_LIMIT_PRICE', sorter: true, filter: true, filterType: 'input', precision: 2 },
        { title: '销售限价', dataIndex: 'LIMIT_PRICE', sorter: true, filter: true, filterType: 'input', precision: 2 },
        { title: '最大库存', dataIndex: 'MAX_STOCK', sorter: true, filter: true, filterType: 'input', precision: 2 },
        { title: '最小库存', dataIndex: 'MIN_STOCK', sorter: true, filter: true, filterType: 'input', precision: 2 },
        { title: '账面库存', dataIndex: 'STOCK_QUANTITY', sorter: true, filter: true, filterType: 'input', precision: 2 },
        { title: '可用库存', dataIndex: 'USEABLE_STOCK', sorter: true, filter: true, filterType: 'input', precision: 2 },
        { title: '锁定量', dataIndex: 'LOCKED_QUANTITY', sorter: true, filter: true, filterType: 'input', precision: 2 },
        { title: '替代配件', dataIndex: 'OPTION_NO', sorter: true, filter: true, filterType: 'input' },
        { title: '替代件库存', dataIndex: 'OPTION_STOCK', sorter: true, filter: true, filterType: 'input' },
        {
          title: '配件类别',
          dataIndex: 'PART_GROUP_CODE',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{this.createDictText(props.row.PART_GROUP_CODE, '8075')}</span>;
          }
        },
        { title: '单位', dataIndex: 'UNIT_NAME', sorter: true, filter: true, filterType: 'input' }
      ];
    },
    // 获取数据字典数据
    async getlist() {
      try {
        let res = await getStroageList({
          // type: 0 去除原厂非原产库限制
        });
        this.storageList = res.data.map(x => ({ value: x.STORAGE_CODE, text: x.STORAGE_NAME }));
        // this.formList1.find(item => item.fieldName === 'storageCode').itemList = this.storageList;
        // this.formList1.find(item => item.fieldName === 'storageCode').initialValue = res.data[0].STORAGE_CODE;
        this.formList2.find(item => item.fieldName == 'STORAGE_CODE').itemList = this.storageList;
      } catch (err) {
        console.err('获取仓库失败', err);
      }

      try {
        const resd = await getBrand();
        this.formList1.find(item => item.fieldName === 'brand').itemList = resd.data.map(x => ({ text: x.BRAND_NAME, value: x.BRAND_CODE + '' }));
        this.formList1.find(item => item.fieldName === 'brand').initialValue = resd.data.find(item => item.BRAND_NAME == '奥迪').BRAND_CODE + '';
      } catch (err) {
        // console.log('获取品牌失败', err);
      }

      // let resdata = await findAllRepair();
      // this.formList1.find(item => item.fieldName === 'storageCode').initialValue = resdata.data['1100'];
    },
    getStroageName(STORAGE_CODE) {
      const item = this.storageList.find(x => {
        return x.value == STORAGE_CODE;
      });
      return item ? item.text : '';
    },
    // 重置
    FormPanelreset() {
      this.$refs.formpanel1.RESET_FORM();
    },
    FormPanelSeacher() {
      this.$refs.formpanel1.SUBMIT_FORM();
      this.$refs.formpanel2.RESET_FORM();
      this.emptyTableData = [];
    },
    // 选中事件
    selectTableFun(val) {
      if (val && val.length > 0) {
        let value = val[0].OPTION_NO;
        this.replacedata = val[0];
        if (value == null) {
          this.isreplace = true;
        } else {
          this.isreplace = false;
        }
      }
    },
    formchangeFun(val) {
      if (val.partNo != null && val.partNo != '') {
        this.pj = true;
      } else {
        this.pj = false;
      }
      this.fetchParams = Object.assign({}, this.fetchParams, val, { xhrAbort: false });
    },
    formchangeFuns(val) {
      console.log(val, '表单数据变化');
      if (this.pd) {
        let json = {};
        // console.log(val, 'val');
        json.IN_QUANTITY = val.IN_QUANTITY;
        json.IN_PRICE = val.inPrice;
        json.IN_AMOUNT = val.inAmount;
        json.STORAGE_POSITION_CODE = val.STORAGE_POSITION_CODE;
        json.partNo = val.partNo;
        json.PART_NAME = val.PART_NAME;
        json.STORAGE_CODE = val.STORAGE_CODE;
        this.formList2
          .find(item => item.fieldName == 'STORAGE_CODE')
          .itemList.forEach(x => {
            if (val.STORAGE_CODE == x.value) {
              json.STORAGE_NAME = x.text;
            }
          });
        json.ITEM_ID = 'N';
        json.FLAG = 'A';
        this.formData = Object.assign({}, json);
        this.pdiShow = true;
      } else {
        this.pd = false;
        this.fromSubmitdata = val; // {...val};
        // let json = this.tableslist[0];
        let json = {};
        json.PART_NO = this.fromSubmitdata.partNo;
        json.PART_NAME = this.fromSubmitdata.PART_NAME;
        json.IN_QUANTITY = this.fromSubmitdata.IN_QUANTITY;
        json.IN_PRICE = this.fromSubmitdata.inPrice;
        json.IN_AMOUNT = this.fromSubmitdata.inAmount;
        json.STORAGE_POSITION_CODE = this.fromSubmitdata.STORAGE_POSITION_CODE;
        json.STORAGE_CODE = this.fromSubmitdata.STORAGE_CODE;
        this.formList2
          .find(item => item.fieldName == 'STORAGE_CODE')
          .itemList.forEach(x => {
            if (this.fromSubmitdata.STORAGE_CODE == x.value) {
              json.STORAGE_NAME = x.text;
            }
          });
        json.ITEM_ID = 'N';
        json.FLAG = 'A';
        console.log(this.partDetailTableData, json);
        let formdata = Object.assign(this.tablelist, this.partDetailTableData, json);
        this.$emit('addNewPart', formdata);
      }
    },
    tableDbclickFun(val) {
      if (val.PART_STATUS == '10041001') {
        this.$notify({
          title: '警告',
          message: '配件已停用',
          type: 'warning'
        });
        return;
      }
      this.tablelist = val;
      this.formList2.find(item => item.fieldName == 'STORAGE_CODE').initialValue = val.STORAGE_CODE;
      this.formList2.find(item => item.fieldName == 'partNo').initialValue = val.PART_NO;
      this.formList2.find(item => item.fieldName == 'PART_NAME').initialValue = val.PART_NAME;
      this.formList2.find(item => item.fieldName == 'inPrice').initialValue = val.PLAN_PRICE;
      this.formList2.find(item => item.fieldName == 'IN_QUANTITY').initialValue = 1;
      this.formList2.find(item => item.fieldName == 'inAmount').initialValue =
        this.formList2.find(item => item.fieldName == 'inPrice').initialValue * this.formList2.find(item => item.fieldName == 'IN_QUANTITY').initialValue;
      this.formList2.find(item => item.fieldName == 'STORAGE_POSITION_CODE').initialValue = val.STORAGE_POSITION_CODE;
      let storageLocation = val.STORAGE_POSITION_CODE;
      this.queryEmptyLocation(val.STORAGE_CODE);
      this.getpartlist(val);
    },
    async getpartlist(val) {
      this.emptyTableData = [];
      let res = (await getaddPartList(val.STORAGE_CODE || '', val.PART_NO)).data.rows;
      this.partDetailTableData = res[0] || {};
      // this.confirmHandle(); 取消双击增加配件 hxj 2020/2/25
      // this.basetables.EXECUTE_INSERT(res);
    },
    changemoney(val) {
      this.formList2.find(item => item.fieldName == 'inAmount').initialValue = (val * this.formList2.find(item => item.fieldName == 'IN_QUANTITY').initialValue).toFixed(2);
    },
    changemNum(val) {
      let money = this.formList2.find(item => item.fieldName == 'inPrice').initialValue;
      this.formList2.find(item => item.fieldName == 'inAmount').initialValue = (val * money).toFixed(2);
    },
    // 关闭弹窗
    closeDialog() {
      this.$emit('close', false);
    },
    tablechangeFun(val) {
      this.tableslist = val;
    },
    // 添加事件提交表单
    confirmHandle() {
      if (this.formList2.find(item => item.fieldName == 'STORAGE_CODE').initialValue === 'OEMK') {
        return this.$notify({ title: '警告信息', message: 'OEM库不能借进入库', type: 'warning' });
      } else {
        this.$refs.formpanel2.SUBMIT_FORM();
      }
    }
  }
};
</script>
